package com.wn.class30.cotroller.weixin;

import com.wn.class30.entity.Integral;
import com.wn.class30.entity.PayOrder;
import com.wn.class30.service.IntegralService;
import com.wn.class30.service.UserService;
import com.wn.class30.service.VipService;
import com.wn.class30.service.WXPayOrderService;
import com.wn.class30.tools.MoneyUtils;
import com.wn.class30.tools.UserIp;
import com.wn.class30.tools.WXPayUtil;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.weixin4j.WeixinConfig;
import org.weixin4j.WeixinException;
import org.weixin4j.WeixinPayConfig;
import org.weixin4j.http.HttpsClient;
import org.weixin4j.http.Response;
import org.weixin4j.model.js.Ticket;
import org.weixin4j.model.pay.UnifiedOrder;
import org.weixin4j.model.pay.UnifiedOrderResult;
import org.weixin4j.model.pay.WCPay;
import org.weixin4j.model.pay.WXPay;
import org.weixin4j.spring.WeixinTemplate;
import org.weixin4j.util.SignUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestMapping(value = "/weixin")
@Controller
@Api(value = "微信测试jspa支付",tags = "微信测试jspa支付")
public class WXPayController {
    @Resource
    private IntegralService integralService;
    @Resource
    private WXPayOrderService wxPayOrderService;
    @Resource
    private WeixinTemplate weixinTemplate;
    @Resource
    private UserService userService;

    @Resource
    private VipService vipService;

    @RequestMapping(value = "/pay/create")
    public String WeixinPay(HttpServletRequest req, Map<String, Object> map) throws WeixinException, IOException, TemplateException {
        UnifiedOrder unifiedOrder = new UnifiedOrder();
        unifiedOrder.setAppid("wxd898fcb01713c658");
        unifiedOrder.setMch_id("1483469312");
        unifiedOrder.setNonce_str(RandomStringUtils.random(16, "abcdefghijklmnopqrstuvwxyz"));
        unifiedOrder.setBody("火锅消费");
        unifiedOrder.setOut_trade_no(UserIp.getOrderIdByTime());
        unifiedOrder.setTotal_fee("1");
        String ipAddress = UserIp.getIpAddress(req);
        System.out.println(ipAddress);
        unifiedOrder.setSpbill_create_ip(ipAddress);
        unifiedOrder.setOpenid("oTgZpwbzXmADFb9_EPipDEWwrebY");
        unifiedOrder.setNotify_url("http://zhouhao1.ngrok2.xiaomiqiu.cn/sell/notify");
        unifiedOrder.setTrade_type("JSAPI");
        Map<String, String> stringStringMap = unifiedOrder.toMap();
        String sign = SignUtil.getSign(stringStringMap, "098F6BCD4621D373CADE4E832627B4F6");
        unifiedOrder.setSign(sign);
        UnifiedOrderResult unifiedOrderResult = weixinTemplate.pay().payUnifiedOrder(unifiedOrder);
        String prepay_id = unifiedOrderResult.getPrepay_id();
        WCPay wcPay = new WCPay("wxd898fcb01713c658", prepay_id, "098F6BCD4621D373CADE4E832627B4F6");
        map.put("payResponse", wcPay);
        return "/sell/pay/create";
//        UnifiedOrderResult unifiedOrderResult = weixinTemplate.pay().payUnifiedOrder(unifiedOrder);
     /*   String xmlPost = unifiedOrder.toXML();
        if (Configuration.isDebug()) {
            System.out.println("调试模式_统一下单接口 提交XML数据：" + xmlPost);
        }

        HttpsClient http = new HttpsClient();
        Response res = http.postXml("http://wchuan.mynatapp.cc/sell/pay/create", xmlPost);
        String xmlResult = res.asString();

        try {
            JAXBContext context = JAXBContext.newInstance(new Class[]{UnifiedOrderResult.class});
            Unmarshaller unmarshaller = context.createUnmarshaller();
            UnifiedOrderResult result = (UnifiedOrderResult)unmarshaller.unmarshal(new StringReader(xmlResult));
            System.out.println(result.getReturn_code());
            System.out.println(result.getReturn_msg());
        } catch (JAXBException var9) {
            System.out.println("-------------------------------------------");
        }
        return null;*/
    }

    @RequestMapping("/payweixinNotifyUrl")
    public String callBack(HttpServletRequest request, HttpServletResponse response) {
        //System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
        InputStream is = null;
        try {
            is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = WXPayUtil.inputStream2String(is, "UTF-8");
            System.out.println(xml);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map
            if (notifyMap.get("return_code").equals("SUCCESS")) {
                if (notifyMap.get("result_code").equals("SUCCESS")) {
                    String ordersSn = notifyMap.get("out_trade_no");//商户订单号
                    String amountpaid = notifyMap.get("total_fee");//实际支付的订单金额:单位 分
                    PayOrder payOrder = wxPayOrderService.queryPayOrderByOrderNum(ordersSn);
                    if (payOrder != null && "0".equals(payOrder.getPayOrderState())) {
                        payOrder.setPayOrderState("1");
                        wxPayOrderService.updatePayOrder(payOrder);
                        Integral integral = integralService.queryIntegral();
                        Double ratio = integral.getRatio();
                        double mul = MoneyUtils.mul(ratio, payOrder.getPayMoney());
                        double floor = Math.floor(mul);
                        userService.updatePointsByUserid(payOrder.getUserId(), (int) floor);
                        vipService.updateVipLv(payOrder.getUserId());
                    }

                    }
                }
                //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
                response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
                is.close();
            } catch(Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

    }


